package com.hx.vending.service.impl;

import com.hx.vending.bean.*;
import com.hx.vending.bean.entity.*;
import com.hx.vending.dao.*;
import com.hx.vending.service.IUserService;
import com.hx.vending.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/11/27.
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FieldMapper fieldMapper;
    @Autowired
    private OnlineOrderMapper onlineOrderMapper;
    @Autowired
    private GoodsConsumeMapper goodsConsumeMapper;
    @Autowired
    private OrderBuyMapper orderBuyMapper;
    @Autowired
    private RefundMapper refundMapper;
    @Resource
    private SubsidiaryRoleMapper subsidiaryRoleMapper;
    @Resource
    private UserOperationMapper userOperationMapper;

    @Override
    public User selectByPrimary(String userPhone) {
        return userMapper.selectByPrimary(userPhone);
    }

    @Override
    public User findByUserPhone(String userPhone) {
        return userMapper.findByUserPhone(userPhone);
    }

    @Override
    public int insertByPhone(User user) {
        return userMapper.insertByPhone(user);
    }

    //发送验证码
    @Override
    public Msg pushMessageByPhone(String phone, String condition) {
        if (null == phone) {
            return Msg.fail().add("msg", "手机号码不能为空");
        }
        String msgId = "";
        if(ToolUtil.isNotEmpty(condition)){
            User user = new User();
            user.setUserPhone(phone);
            //查询User对象
            User u = userMapper.selectByPrimaryKey(user);
            if(condition.equals("register")){
                if(ToolUtil.isNotEmpty(u)){
                    return Msg.fail().add("msg", "该手机号码已注册");
                }
            }else if(condition.equals("forget")){
                if(ToolUtil.isEmpty(u)){
                    return Msg.fail().add("msg","该手机号码未注册");
                }
            }
            msgId = JPushUtils.sendSMSCode(phone);
            return Msg.success().add("msgId", msgId);
        }else{
            //如果查询条件为空，则不为注册发送验证码
            return Msg.fail();
        }
    }
    @Override
    public Msg verifyCode(String code,String msgId){
        if(ToolUtil.isEmpty(code)){
            return Msg.fail().add("msg", "参数不能为空");
        }
        if (!JPushUtils.sendValidSMSCode(msgId, code)) {
            return Msg.fail().add("msg", "验证码错误");
        }
        return Msg.success();
    }
    @Override
    public int updatePassword(String userPhone,String userPassWord){
        return userMapper.updatePassword(userPhone,userPassWord);
    }

    @Override
    public Msg getUnderOrderTod(Integer userId, List<Integer> fieldList, String startTime, String endTime) {
        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("va_msg", "用户信息不能为空");
        }
        // 首先校验用户是否存在
        User user = new User();
        user.setUserId(userId);

        User checkUser = this.userMapper.selectByPrimaryKey(user);
        if (ToolUtil.isEmpty(checkUser)) {
            return Msg.fail().add("va_msg", "用户不存在");
        }
        if (CollectionUtils.isEmpty(fieldList)) {

            fieldList = null;
        }
        // 获取所有线下投币详情
        Double mapList = this.onlineOrderMapper.selectUnderLineByUserId(userId,startTime,endTime,fieldList);

        return Msg.success().add("va_msg", mapList);
    }

    @Override
    public Msg getOnlineOrderTod(Integer userId, List<Integer> fieldList, String startTime, String endTime) {
        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("va_msg", "用户信息不能为空");
        }
        // 首先校验用户是否存在
        User user = new User();
        user.setUserId(userId);

        User checkUser = this.userMapper.selectByPrimaryKey(user);
        if (ToolUtil.isEmpty(checkUser)) {
            return Msg.fail().add("va_msg", "用户不存在");
        }
        if (CollectionUtils.isEmpty(fieldList)) {

            fieldList = null;
        }
        Double sumOnlineOrderNumber = this.onlineOrderMapper.selectSumOnlineOrderNumber(userId, fieldList, startTime, endTime);
        /*Double moneyFile = orderBuyMapper.selectMoneyFile(userId,fieldList, startTime, endTime);
        Double money = BigDecimalUtils.sub(sumOnlineOrderNumber,moneyFile);*/
        return Msg.success().add("sumOnlineOrderNumber", sumOnlineOrderNumber);
    }

    @Override
    public Double getEarningsToday(Integer userId, List<Integer> fieldList, String startTime, String endTime) {
        if (CollectionUtils.isEmpty(fieldList)) {

            fieldList = null;
        }
        /*Double sumOnlineOrderNumber = this.onlineOrderMapper.selectSumOnlineOrderNumber(userId, fieldList, startTime, endTime);*/
        Double moneyFile = orderBuyMapper.selectMoneyFile(userId,fieldList, startTime, endTime);
        /*Double money = BigDecimalUtils.sub(sumOnlineOrderNumber,moneyFile);*/
        return moneyFile;
    }

    @Override
    public Msg statisticalGain(Integer userId,Integer[] integers, String condition) {
        SimpleDateFormat sdf;
        //返回的结果Map
        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        //返回的list
        List<Map<String, Object>> resultListMap = new ArrayList<>();
        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("msg", "用户信息不能为空");
        }
        if (ToolUtil.isEmpty(condition)) {
            return Msg.fail().add("msg", "查询条件不能为空");
        } else {
            if (!condition.equals("day") && !condition.equals("month")) {
                return Msg.fail().add("msg", "错误的查询条件");
            }
        }
        //条件查询开始/结束时间
        String startTime = "";
        String endTime = ToolUtil.currentTime();
        //循环遍历次数
        int num = 0;
        //时间转换格式
        String dateFormat = "";
        /**
         *日期时间 若以天计算则以2018-5-12格式
         * 		   若以月计算则以2018-5格式
         */
        //查询近30天的每天收益统计
        if(condition.equals("day")){
            sdf = new SimpleDateFormat("yyyy-MM-dd");
            //前三十天
            startTime = ToolUtil.getDayTime(0, 0, -30, "yyyy-MM-dd");
            //先提前插入30个map数据，key为30天的日期.value暂时为空，在下面遍历添加
            for (int i = 0; i < 30; i++) {
                resultMap.put(ToolUtil.getDayTime(0, 0, -i, "yyyy-MM-dd"), new HashMap());
            }
            //修改循环遍历次数和转换格式
            num = 30;
            dateFormat = "yyyy-MM-dd";
        }else{
            //查询近半年的每天收益统计
            sdf = new SimpleDateFormat("yyyy-MM");
            //修改循环遍历次数和转换格式
            num = 6;
            dateFormat = "yyyy-MM";
            //当前月份减去五个月的那个月的第一天。半年时间
            startTime = ToolUtil.getFirstDayOfMonth(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH) - 4);
            for (int i = 0; i < 6; i++) {
                resultMap.put(ToolUtil.getDayTime(0, -i, 0, "yyyy-MM"), new HashMap());
            }
        }
        //查询线上投币总数
        List<Map<String, Object>> onlineOrderMapList = onlineOrderMapper.selectOrderOnlineAmountByTime(userId, startTime, endTime,integers);
        List<Map<String,Object>> refundMapList = refundMapper.selectRefundByTime(userId,startTime,endTime,integers);
        //查询线下总钱数
        List<Map<String, Object>> underlineOrderMapList = onlineOrderMapper.selectUnderOrderAmountByTime(userId,startTime,endTime,integers);
        //消耗礼品总数和总价钱
        List<Map<String, Object>> goodsConsumeMapList = goodsConsumeMapper.selectAmountAndCountByTime(userId, startTime, endTime,integers);

       /* if(num == 6){
            num = 1;
        }*/
        for(int i = 0;i < num;i++){
            try {
                //循环onlineOrderMapList遍历获取每一个map
                for (Map onlineMap : onlineOrderMapList) {
                    //获取每一条数据中的时间
                    String onlineOrderTime = (String) onlineMap.get("onlineOrderTime");
                    //格式化日期
                    String formatDate = sdf.format(sdf.parse(onlineOrderTime));
                    String date = "";
                    if(num == 6){
                        date = ToolUtil.getDayTime(0, -i, 0, dateFormat);
                    }else{
                        date = ToolUtil.getDayTime(0, 0, -i, dateFormat);
                    }
                    //循环插入的i天对比循环遍历的日期，如果相等,则放数据。如果不相等，则只是put进去当天日期
                    if (date.equals(formatDate)) {
                        Map<String, Object> map = resultMap.get(date);
                        if (null == map.get("onlineOrderAmount")) {//null证明第一次向这个日期插入数据，不需要累加
                            map.put("onlineOrderAmount", onlineMap.get("onlineOrderAmount"));
                        } else {
                            map.put("onlineOrderAmount", BigDecimalUtils.add(Double.parseDouble(map.get("onlineOrderAmount").toString()),Double.parseDouble(onlineMap.get("onlineOrderAmount").toString())));
                        }
                        resultMap.put(date, map);
                    }
                }
                for(Map<String,Object> refundMap:refundMapList){
                    String refundTime = refundMap.get("refundTime").toString();
                    //格式化日期
                    String formatDate = sdf.format(sdf.parse(refundTime));
                    String date = "";
                    if(num == 6){
                        date = ToolUtil.getDayTime(0, -i, 0, dateFormat);
                    }else{
                        date = ToolUtil.getDayTime(0, 0, -i, dateFormat);
                    }
                    if(date.equals(formatDate)){
                        Map<String, Object> map = resultMap.get(date);
                        if (null != map.get("onlineOrderAmount")) {//null证明第一次向这个日期插入数据，不需要累加
                            map.put("onlineOrderAmount", BigDecimalUtils.sub(Double.parseDouble(map.get("onlineOrderAmount").toString()),
                                    Double.parseDouble(refundMap.get("moneyFile").toString())));
                        }
                        resultMap.put(date, map);
                    }
                }
                //循环underlineOrderMapList遍历获取每一个map
                for(Map underlineMap:underlineOrderMapList){
                    //获取ubderlineTime进行日期格式转换
                    String underlineTime = (String) underlineMap.get("underlineTime");
                    //获取到格式化的时间
                    String formatTime = sdf.format(sdf.parse(underlineTime));
                    String date;
                    if(num == 6){
                        date = ToolUtil.getDayTime(0, -i, 0, dateFormat);
                    }else{
                        date = ToolUtil.getDayTime(0, 0, -i, dateFormat);
                    }
                    //时间对比是否同一天
                    if (formatTime.equals(date)) {
                        Map<String, Object> map = resultMap.get(date);
                        if (null == map.get("underlineAmount")) {//null证明第一次向这个日期插入数据，不需要累加
                            map.put("underlineAmount", underlineMap.get("underlineAmount"));
                        } else {
                            map.put("underlineAmount", BigDecimalUtils.add(Double.parseDouble(map.get("underlineAmount").toString()),Double.parseDouble(underlineMap.get("underlineAmount").toString())));
                        }
                        resultMap.put(date, map);
                    }
                }
                //循环遍历goodsConsumeMapList获取每一个map
                for(Map goodsMap:goodsConsumeMapList){
                    //获取ubderlineTime进行日期格式转换
                    String consumeTime = goodsMap.get("consumeTime").toString();
                    //获取到格式化的时间
                    String formatTime = sdf.format(sdf.parse(consumeTime));
                    String date;
                    if(num == 6){
                        date = ToolUtil.getDayTime(0, -i, 0, dateFormat);
                    }else{
                        date = ToolUtil.getDayTime(0, 0, -i, dateFormat);
                    }
                    //时间对比是否同一天
                    if (formatTime.equals(date)) {
                        Map<String, Object> map = resultMap.get(date);
                        if (null == map.get("goodsPriceAmount")) {//null证明第一次向这个日期插入数据，不需要累加
                            map.put("goodsPriceAmount", goodsMap.get("goodsPriceAmount"));
                            map.put("goodsCount", goodsMap.get("goodsCount"));
                        } else {
                            map.put("goodsPriceAmount",BigDecimalUtils.add (Double.parseDouble(map.get("goodsPriceAmount").toString()),Double .parseDouble(goodsMap.get("goodsPriceAmount").toString())));
                            map.put("goodsCount", BigDecimalUtils.add(Double.parseDouble(map.get("goodsCount").toString()),Double.parseDouble(goodsMap.get("goodsCount").toString())));
                        }
                        resultMap.put(date, map);
                    }
                }
            }catch (ParseException e){
                    e.printStackTrace();
            }
        }
        //总钱数
        for(String key : resultMap.keySet()){
            Double underlineAmount = 0D;
            Double onlineOrderAmount = 0D;
            //key为时间
            Map<String, Object> map = resultMap.get(key);
            if(ToolUtil.isNotEmpty(map.get("goodsPriceAmount"))){
                Double goodsPriceAmount = Double.parseDouble(map.get("goodsPriceAmount").toString());
                map.put("goodsPriceAmount",goodsPriceAmount);
            }else{
                map.put("goodsPriceAmount",0D);
            }
            if(ToolUtil.isNotEmpty(map.get("goodsCount"))){
                Double goodsCount = Double.parseDouble(map.get("goodsCount").toString());
                map.put("goodsCount",goodsCount);
            }else{
                map.put("goodsCount",0D);
            }
            if(ToolUtil.isNotEmpty(map.get("underlineAmount"))){
                underlineAmount = Double.parseDouble(map.get("underlineAmount").toString());
                map.put("underlineAmount",underlineAmount);
            }else{
                map.put("underlineAmount",0D);
            }
            if(ToolUtil.isNotEmpty(map.get("onlineOrderAmount"))){
                onlineOrderAmount = Double.parseDouble(map.get("onlineOrderAmount").toString());
                map.put("onlineOrderAmount",onlineOrderAmount);
            }else{
                map.put("onlineOrderAmount",0D);
            }
            //时间和总数 总数查询订单表信息
            if (ToolUtil.isNotEmpty(map.get("underlineAmount")) || ToolUtil.isNotEmpty(map.get("onlineOrderAmount"))) {
                Double orderAmount;
                if(ToolUtil.isNotEmpty(map.get("underlineAmount")) && ToolUtil.isEmpty(map.get("onlineOrderAmount"))){
                    orderAmount = Double.parseDouble(map.get("underlineAmount").toString()) + 0D;
                }else if(ToolUtil.isEmpty(map.get("underlineAmount")) && ToolUtil.isNotEmpty(map.get("onlineOrderAmount"))){
                    orderAmount = 0D + Double.parseDouble(map.get("onlineOrderAmount").toString());
                }else {
                    orderAmount = Double.parseDouble(map.get("underlineAmount").toString()) + Double.parseDouble(map.get("onlineOrderAmount").toString());
                }
                map.put("amount", orderAmount);
            } else {
                map.put("amount", 0);
            }
            map.put("time", key);
            if (!resultListMap.contains(map)) {
                resultListMap.add(map);
            }
        }
        if(resultListMap.size() == 6){
            ListSortTime(resultListMap);
        }else{
            ListSort(resultListMap);
        }

        return Msg.success().add("data", resultListMap);
    }

    @Override
    public User selectByPrimaryKey(User user) {
        return userMapper.selectByPrimaryKey(user);
    }

    @Override
    public int updateByPrimaryKeySelective(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Msg getNumberByUserId(Integer userId) {
        if(ToolUtil.isEmpty(userId) && userId == 0){
            return Msg.fail().add("msg", "代理商id不能为空");
        }
        User user = new User();
        user.setUserId(userId);
        user = userMapper.selectByPrimaryKey(user);
        if(ToolUtil.isEmpty(user)){
            return Msg.fail().add("msg", "通过代理商id查询的代理商为空");
        }
        return Msg.success().add("serviceWeChat", user.getUserServiceWechat())
                .add("serviceWeChatQr", user.getUserServiceWechatQr())
                .add("servicePhone", user.getUserServicePhone());
    }

    @Override
    public Msg updateCustomService(User user) {
        if(ToolUtil.isEmpty(user)){
            return Msg.fail().add("msg", "用户对象为空");
        }
        if(ToolUtil.isEmpty(user.getUserId())){
            return Msg.fail().add("msg", "用户id不能为空");
        }
        int result = userMapper.updateByPrimaryKeySelective(user);
        if(result != 0){
            return Msg.success().add("va_msg","设置成功");
        }else{
            return Msg.fail().add("va_msg","设置失败");
        }
    }

    @Override
    public Msg updateuserServicePhone(Integer userId, String userServicePhone) {
        User user = new User();
        user.setUserId(userId);
        User u = userMapper.selectByPrimaryKey(user);
        if(ToolUtil.isNotEmpty(u)){
            u.setUserServicePhone(userServicePhone);
            int result = userMapper.updateByPrimaryKeySelective(u);
            if (result != 0) {
                return Msg.success().add("va_msg", "设置成功");
            } else {
                return Msg.fail().add("va_msg", "设置失败");
            }
        }else{
            return Msg.fail().add("va_msg", "未找到该商家信息");
        }
    }

    @Override
    public Msg updateuserMerchantName(Integer userId, String userMerchantName) {
        User user = new User();
        user.setUserId(userId);
        User u = userMapper.selectByPrimaryKey(user);
        if(ToolUtil.isNotEmpty(u)){
            u.setUserMerchantName(userMerchantName);
            int result = userMapper.updateByPrimaryKeySelective(u);
            if (result != 0) {
                return Msg.success().add("va_msg", "设置成功");
            } else {
                return Msg.fail().add("va_msg", "设置失败");
            }
        }else{
            return Msg.fail().add("va_msg", "未找到该商家信息");
        }
    }

    @Override
    public Msg getUserByUserId(Integer userId,Integer account) {
        if(ToolUtil.isEmpty(userId) || userId == 0){
            return Msg.fail().add("msg", "参数值错误");
        }
        if(account != 0){
            userId = account;
        }
        User user = new User();
        user.setUserId(userId);
        user = userMapper.selectByPrimaryKey(user);
        if(ToolUtil.isEmpty(user)){
            return Msg.fail().add("msg", "根据代理商id查询的信息对象为空");
        }
        return Msg.success().add("user", user);
    }

    @Override
    public List<User> selectByExample(User user) {
        return userMapper.selectByExample(user);
    }

    @Override
    public List<RegionVo> selectRegionOne() {
        return userMapper.selectRegionOne();
    }

    @Override
    public List<RegionDetailVo> selectRegionVoByPid(Integer regionPid) {
        return userMapper.selectRegionVoByPid(regionPid);
    }

    @Override
    public List<Region> selectRegionByPid(Integer regionPid) {
        return userMapper.selectRegionByPid(regionPid);
    }

    @Override
    public UserService selectUserServiceById(Integer userId) {
        return userMapper.selectUserServiceById(userId);
    }

    @Override
    public int deleteByPrimaryKey(Integer userId) {
        return userMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public User selectUserById(Integer userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public UserVO selectBankByUserId(Integer userId) {
        return userMapper.selectBankByUserId(userId);
    }

    @Override
    public List<UserAudit> selectUserBankList(String userName, String state, String startTime, String endTime,Integer pageStart) {
        return userMapper.selectUserBankList(userName,state,startTime,endTime,pageStart);
    }

    @Override
    public Integer selectUserNum(String userName, String userPhone) {
        return userMapper.selectUserNum(userName,userPhone);
    }

    @Override
    public List<User> selectUserBack(Map<String, Object> map) {
        return userMapper.selectUserBack(map);
    }


    //按时间排序
    private static void ListSort(List<Map<String, Object>> list) {
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> map1, Map<String, Object> map2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date dt1 = format.parse(map1.get("time").toString());
                    Date dt2 = format.parse(map2.get("time").toString());
                    if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }
    //按时间排序
    private static void ListSortTime(List<Map<String, Object>> list) {
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> map1, Map<String, Object> map2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                try {
                    Date dt1 = format.parse(map1.get("time").toString());
                    Date dt2 = format.parse(map2.get("time").toString());
                    if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }


    /**
     * 保存商户提现信息
     * @param userId
     * @param user
     * @return
     */
    public Msg updateUserDrawCashMessage(Integer userId, User user) {

        if (ToolUtil.isNotEmpty(userId)) {

            user.setUserId(userId);

            //查询商户信息
            User user1 = new User();
            user1.setUserId(userId);
            User selectUser = this.userMapper.selectByPrimaryKey(user1);

            //绑定微信信息
            if (ToolUtil.isNotEmpty(selectUser)) {
                if (ToolUtil.isNotEmpty(selectUser.getUserPreviewCustomerId())) {
                    user.setUserCustomerId(selectUser.getUserPreviewCustomerId());
                }
            }else {
                return Msg.fail();
            }

            int i = this.userMapper.updateByPrimaryKeySelective(user);
            //删除预存的微信授权信息
            this.userMapper.updateCustomerIdNull(user);

            if (i != 0) {
                return Msg.success();
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail().add("msg", "用户id为空");
        }
    }

    @Override
    public int updateSecondaryPassword(String userPhone, String userPassWord) {
        return userMapper.updateSecondaryPassword(userPhone, userPassWord);
    }

    /**
     * 验证二级密码
     * @param userId
     * @param secondaryPassword
     * @return
     */
    public Msg selectVerificationSecondaryPassword(Integer userId, String secondaryPassword) {

        if (ToolUtil.isNotEmpty(userId) || ToolUtil.isNotEmpty(secondaryPassword)) {

            User user = new User();
            user.setUserId(userId);
            User selectUser = this.userMapper.selectByPrimaryKey(user);
            if (ToolUtil.isNotEmpty(selectUser)) {

                if (ToolUtil.isEmpty(selectUser.getUserSecondaryPassword())) {
                    return Msg.fail().add("msg", "未设置二级密码");
                }

                if (selectUser.getUserSecondaryPassword().equals(MD5.string2MD5(secondaryPassword))) {
                    return Msg.success();
                }else {
                    return Msg.fail();
                }
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail().add("msg", "用户id或二级密码为空");
        }
    }

    /**
     * 查询商户提现比例
     * @param userId
     * @return
     */
    public Msg selectUserWithdrawProportion(Integer userId) {

        if (ToolUtil.isNotEmpty(userId)) {

            User user = new User();
            user.setUserId(userId);
            User selectUser = this.userMapper.selectByPrimaryKey(user);

            if (ToolUtil.isNotEmpty(selectUser)) {

                return Msg.success().add("userWithdrawProportion", selectUser.getUserWithdrawproportion());
            }else {
                return Msg.fail().add("msg", "该商户不存在");
            }
        }else {
            return Msg.fail().add("msg", "用户id为空");
        }
    }


    /**
     * 修改商户体现比例
     * @param userId
     * @return
     */
    public Msg updateUserWithdrawProportion(Integer userId, Float withdrawProportion) {

        if (ToolUtil.isNotEmpty(userId) && ToolUtil.isNotEmpty(withdrawProportion)) {

            User user = new User();
            user.setUserId(userId);
            user.setUserWithdrawproportion(withdrawProportion);
            int i = this.userMapper.updateByPrimaryKeySelective(user);

            if (i != 0) {

                return Msg.success();
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail().add("msg", "用户id为空");
        }
    }

    @Override
    public int deleteBatchByList(List<Integer> integerList) {
        return userMapper.deleteBatchByList(integerList);
    }

    @Override
    public Msg selectSubAccount(Integer userId,String userName) {
        try {
            List<SubAccount> map = userMapper.selectUserByUserId(userId,userName);
            return Msg.success().add("userList",map);
        }catch (Exception e){
            return Msg.fail();
        }

    }

    @Override
    public Msg selectSubAccountDetails(Integer account) {
        try {
            SubAccount map = userMapper.selectDetailsByUserId(account);
            return Msg.success().add("userList",map);
        }catch (Exception e){
            return Msg.fail();
        }
    }

    @Override
    public int updateSubAccount(Integer userId,String userName, String userPassWord,String userPhone,String roleId,String fieldId) {
        return userMapper.updateSubAccount(userId,userName,userPassWord,userPhone,roleId,fieldId);
    }

    @Override
    public Msg editSubAccountUse(Integer account, Integer subsidiaryUse) {
        int i = userMapper.updateSubAccountUse(account,subsidiaryUse);
        if (i > 0){
            return Msg.success();
        }
        return Msg.fail();
    }

    @Override
    public User selectUserDetailsById(Integer userId) {
        return userMapper.selectUserDetailsById(userId);
    }

    /**
     * 查询登陆账号的权限
     * @param userId
     * @return
     */
    @Override
    public Msg selectUserOperation(Integer userId) {
        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("msg", "商户未登录");
        }else if(userId == 0){
            return Msg.fail().add("msg","该账户为主账户");
        }

        List<UserOperation> userOperations = new ArrayList<UserOperation>();
        List<Object> Super = new ArrayList<Object>();

        //查询登陆的用户信息
        User user = new User();
        user.setUserId(userId);
        User selectUser = this.userMapper.selectByPrimaryKey(user);

        if (ToolUtil.isEmpty(selectUser)) {
            return Msg.fail().add("msg", "该商户不存在");
        }

        //保存登录用户的信息
        LoginUserOperation loginUserOperation = new LoginUserOperation();
        loginUserOperation.setUserId(selectUser.getUserId());
        loginUserOperation.setUserRole(selectUser.getUserRole());
        loginUserOperation.setUserSubsidiaryUse(selectUser.getUserSubsidiaryUse());
        if (ToolUtil.isEmpty(selectUser.getUserFather())) {
            loginUserOperation.setUserSuper("0");//0父用户为空，登陆的为普通用户
        }else {
            loginUserOperation.setUserSuper("1");//登陆的为子账号
            String[] filed = selectUser.getUserFieldId().split(",");
            loginUserOperation.setUserFieldId(filed);

            //子账户查询用户的权限
            //查询岗位信息
            SubsidiaryRole subsidiaryRole = new SubsidiaryRole();
            subsidiaryRole.setSubsidiaryRoleId(Integer.parseInt(selectUser.getUserRole()));
            SubsidiaryRole selectSubsidiaryRole = this.subsidiaryRoleMapper.selectByPrimaryKeySelective(subsidiaryRole);

            if (ToolUtil.isNotEmpty(selectSubsidiaryRole) && ToolUtil.isNotEmpty(selectSubsidiaryRole.getSubsidiaryRoleOperation())) {
                String[] operationId = selectSubsidiaryRole.getSubsidiaryRoleOperation().split(",");

                for (String opid: operationId) {
                    //查询权限信息
                    UserOperation userOperation = new UserOperation();
                    userOperation.setOperationId(Integer.parseInt(opid));
                    UserOperation selectUserOperation = this.userOperationMapper.selectByPrimaryKeySelective(userOperation);
                    userOperations.add(selectUserOperation);
                }
                //权限分级
                for (UserOperation uo: userOperations) {
                    if (ToolUtil.isEmpty(uo.getOperationSuperId())) {

                        UserOperationShow superOperation = new UserOperationShow();
                        superOperation.setOperationId(uo.getOperationId());
                        superOperation.setOperationCreateTime(uo.getOperationCreateTime());
                        superOperation.setOperationName(uo.getOperationName());
                        superOperation.setOperationPath(uo.getOperationPath());
                        superOperation.setOperationRemark(uo.getOperationRemark());
                        superOperation.setOperationSuperId(uo.getOperationSuperId());
                        superOperation.setOperationTitle(uo.getOperationTitle());

                        List<Object> son = new ArrayList<Object>();
                        for (UserOperation sonuo: userOperations) {
                            if (ToolUtil.isNotEmpty(sonuo.getOperationSuperId())) {
                                if (sonuo.getOperationSuperId() == uo.getOperationId()) {
                                    son.add(sonuo);
                                }
                            }
                        }

                        superOperation.setSuperOperation(son);
                        Super.add(superOperation);
                    }
                }
                loginUserOperation.setOperationList(Super);
            }else {
                return Msg.fail().add("msg", "用户角色不存在");
            }
        }
        return Msg.success().add("userOperation", loginUserOperation);
    }

}
